<template>
  <div class="atr-list">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="refreshText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <articleItem v-for="item in list" :key="item.id" :article="item" />
        <!-- <van-cell v-for="item in list" :key="item.id" :title="item.title" /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import articleItem from '../../../components/article-item/index'
import { getArticles } from '../../../api/article'
export default {
  name: 'ArticleList',
  data() {
    return {
      //存储到列表数据的数组
      list: [],
      //控制加载中loading状态
      loading: false,
      //控制数据加载结束的状态
      finished: false,
      //请求获取下一页数据的时间戳
      timestamp: null,
      error: false,
      isLoading: false,
      refreshText: '刷新成功！'
    };
  },

  mounted() {

  },
  components: {
    articleItem
  },
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  methods: {
    // 初始化或滚动到底部的时候会触发调用onload()
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })
        // console.log(data)
        // if (Math.random() > 0.5) {
        //   JSON.parse('hgdsjdgsj')
        // }
        // 2.把请求结果放到list数组
        const { results } = data.data
        this.list.push(...results)
        // 3.将本次数据加载结束后把加载状态设置为结束
        this.loading = false
        // 4.判断数据是否全部加载完成
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没有数据了，将finished设置为true,不再load加载更多
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        // 1.请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // console.log(data)
        // if (Math.random() > 0.5) {
        //   JSON.parse('hgdsjdgsj')
        // }
        // 2.把请求结果放到list数组
        const { results } = data.data
        this.list.unshift(...results)
        this.refreshText = `刷新成功！更新了${results.length}条数据`
        // 3.将本次数据加载结束后把加载状态设置为结束
        this.isLoading = false
      } catch (err) {
        this.refreshText = '刷新失败！'
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.atr-list {
  height: 79vh;
  overflow-y: auto;
}
</style>